/*
 * Created on Jul 13, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.dsz.du.mealbooking.services;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.dsz.du.mealbooking.commands.LoginCommand;
import com.dsz.du.mealbooking.dao.UserDao;
import com.dsz.du.mealbooking.exceptions.UserHasExistException;
import com.dsz.du.mealbooking.model.UserModel;

/**
 * 
 * @author du
 *
 */
@Service
public class UserService {
	
	public UserService(){}
	
	@Autowired
	@Qualifier("userDao")
	private UserDao userDao;	
	private static Logger logger = Logger.getLogger(UserService.class);
	
	public boolean authenticate(LoginCommand command) throws Exception{
		
		//Check input data.
		if(command.getUserId()!= null && command.getUserId().equalsIgnoreCase("admin") 
				&& command.getPassword()!= null && command.getPassword().equalsIgnoreCase("dgq")){	
			if (logger.isDebugEnabled()){
				logger.debug("Login sucessful.");
			}
			return true;
		}else{			
			UserModel userModel = userDao.getUser(command.getUserId());
			if (userModel == null){
				if (logger.isDebugEnabled()){
					logger.debug("There is no UserModel in DB. UserId is :" + command.getUserId());
				}
				return false;
			}
			String serverPassword = userModel.getPassword();
			String inputPassword = command.getPassword();
			if (inputPassword.equals(serverPassword)){
				if (logger.isDebugEnabled()){
					logger.debug("input UserId is :" + command.getUserId());
					logger.debug("userId is :" + userModel.getUserId());
					logger.debug("passWord is :" + userModel.getPassword());
					logger.debug("name is :" + userModel.getName());
					logger.debug("email is :" + userModel.getMailAddress());					
				}				
				return true;
			} else {
				if (logger.isDebugEnabled()){
					logger.debug("User id is not authenticated.");
				}
				return false;				
			}
		}
	}
	
	public boolean register(UserModel userModel) throws UserHasExistException{
		if (logger.isDebugEnabled()){
			logger.debug("regest user.");
		}
		String userId = userModel.getUserId();
		UserModel savedUserModel = userDao.getUser(userId);
		if (savedUserModel == null){
			userDao.registerUser(userModel);
			return true;
		} else {
			logger.warn("The userId "+ userId + "has been used.");
			throw new UserHasExistException();
		}	
	}

	public UserModel getUserById(String userId) {
		UserModel userModel = userDao.getUser(userId);
		return userModel;
	}
			
	

}
